/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package presentation.view;

import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import presentation.controller.ControlPanelMyAccount;
import presentation.controller.ControlPanelNotes;
import vo.GradesVO;
import vo.SubjectVO;

/**
 *
 * @author Joanna 8a
 */
public class PanelAddGrade extends javax.swing.JPanel implements Subject {

    private AuxiliarFrame parent;
    private List<Observer> observers;
    private GradesVO gradeToUpdate;
    public static final int ADD = 1;
    public static final int UPDATE = 2;

    /**
     * Creates new form PanelAddGrade
     */
    public PanelAddGrade(AuxiliarFrame parent, int selectedIndex, int option, GradesVO gradeToUpdate) {
        this.parent = parent;
        parent.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/presentation/view/images/Calendar.png")).getImage());
        this.gradeToUpdate = gradeToUpdate;
        initComponents();
        jTextFieldOtro.setEnabled(false);
        fillComboBoxSubjects();
        if (selectedIndex >= 0) {
            jComboBoxSubjects.setSelectedIndex(selectedIndex);
            jComboBoxSubjects.setEnabled(false);
        }
        
        switch (option) {
            case ADD:
                setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Añadir Calificación", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI Light", 1, 14), new java.awt.Color(153, 0, 255)));
                jButtonSave.setText("Guardar");
                jSpinnerPonderation.setModel(new javax.swing.SpinnerNumberModel(0.0, 0.0, calculateMaxPercentage(0), 1.0));
                break;
            case UPDATE:
                setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Modificar Calificación", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI Light", 1, 14), new java.awt.Color(153, 0, 255)));
                jButtonSave.setText("Modificar");
                jSpinnerPonderation.setModel(new javax.swing.SpinnerNumberModel(0.0, 0.0, calculateMaxPercentage(gradeToUpdate.getPercentage()), 1.0));
                fillfields();
                break;
        }
        observers = new ArrayList<>();
    }

    private double calculateMaxPercentage(double currentPercentage) {
        double maxPercentage = 0.0;
        for (GradesVO grade : ((SubjectVO) jComboBoxSubjects.getSelectedItem()).getGroups().get(0).getGrades()) {
            maxPercentage += grade.getPercentage();
        }
        return (1 - maxPercentage + currentPercentage) * 100;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jSpinnerGradeValue = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        jSpinnerPonderation = new javax.swing.JSpinner();
        jLabel3 = new javax.swing.JLabel();
        jLabelTotalValue = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jComboBoxTipo = new javax.swing.JComboBox();
        jButtonSave = new javax.swing.JButton();
        jTextFieldOtro = new javax.swing.JTextField();
        jComboBoxSubjects = new javax.swing.JComboBox();
        jButtonCancel = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Añadir Calificación", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI Light", 1, 14), new java.awt.Color(153, 0, 255))); // NOI18N

        jLabel1.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jLabel1.setText("Calificación");

        jSpinnerGradeValue.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        Number step = new Double (0.1);
        jSpinnerGradeValue.setModel(new javax.swing.SpinnerNumberModel(0.0, 0.0, 5.0, step));
        jSpinnerGradeValue.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSpinnerGradeValueStateChanged(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jLabel2.setText("Porcentaje");

        jSpinnerPonderation.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jSpinnerPonderation.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSpinnerPonderationStateChanged(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jLabel3.setText("Total");

        jLabelTotalValue.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jLabelTotalValue.setText("0");

        jLabel5.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jLabel5.setText("Tipo");

        jComboBoxTipo.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jComboBoxTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Taller", "Laboratorio", "Parcial", "Quiz", "Trabajo", "Proyecto", "Otro" }));
        jComboBoxTipo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxTipoActionPerformed(evt);
            }
        });

        jButtonSave.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jButtonSave.setText("Guardar");
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });

        jTextFieldOtro.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jTextFieldOtro.setForeground(new java.awt.Color(51, 51, 255));
        jTextFieldOtro.setText("Otro");
        jTextFieldOtro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldOtroActionPerformed(evt);
            }
        });

        jComboBoxSubjects.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jComboBoxSubjects.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Materia" }));
        jComboBoxSubjects.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxSubjectsActionPerformed(evt);
            }
        });

        jButtonCancel.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jButtonCancel.setText("Cancelar");
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Segoe UI Light", 0, 12)); // NOI18N
        jLabel4.setText("%");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(100, 100, 100)
                                .addComponent(jButtonSave))
                            .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jComboBoxTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jSpinnerGradeValue, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jSpinnerPonderation, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel4)))))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jTextFieldOtro, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButtonCancel)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabelTotalValue, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(0, 34, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBoxSubjects, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jComboBoxSubjects, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jSpinnerPonderation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(jLabelTotalValue)
                            .addComponent(jSpinnerGradeValue, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(37, 37, 37)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jComboBoxTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldOtro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonSave)
                    .addComponent(jButtonCancel))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
        GradesVO grade = new GradesVO();
        Double value = (Double) jSpinnerGradeValue.getValue();
        grade.setValue(value);
        Double perc = new Double(((Double) jSpinnerPonderation.getValue()) / 100);
        grade.setPercentage(perc);
        grade.setTotal();
        grade.setGroupId(((SubjectVO) jComboBoxSubjects.getSelectedItem()).getGroups().get(0).getId());
        if (!jComboBoxTipo.getSelectedItem().toString().equals("Otro")) {
            grade.setType(jComboBoxTipo.getSelectedItem().toString());
        } else {
            grade.setType(jTextFieldOtro.getText());
        }
        switch (jButtonSave.getText()) {
            case "Guardar":
                String result = new ControlPanelNotes().addGrade(grade);
                if (result.equals("OK")) {
                    JOptionPane.showMessageDialog(parent, "La calificacion ha sido agregada satisfactoriamente", result, JOptionPane.INFORMATION_MESSAGE,
                            new ImageIcon(getClass().getResource("/presentation/view/images/Ok.png")));
                    parent.dispose();
                } else {
                    JOptionPane.showMessageDialog(parent, "Ha ocurrido un error y la calificacion no pudo ser agregada", "Ooops!!!", JOptionPane.ERROR_MESSAGE,
                            new ImageIcon(getClass().getResource("/presentation/view/images/Exclamation.png")));
                }
                if (jComboBoxTipo.getSelectedItem().equals("Otro") && jTextFieldOtro.getText().equals("")) {
                    JOptionPane.showMessageDialog(parent, "Se debe proporcionar un Tipo de Calificación", "Error!!!", JOptionPane.ERROR_MESSAGE);
                }
                break;
            case "Modificar":
                grade.setId(gradeToUpdate.getId());
                if (new ControlPanelNotes().updateGrade(grade)) {
                    JOptionPane.showMessageDialog(parent, "La calificacion ha sido modificada satisfactoriamente", "OK", JOptionPane.INFORMATION_MESSAGE,
                            new ImageIcon(getClass().getResource("/presentation/view/images/Ok.png")));
                    parent.dispose();
                } else {
                    JOptionPane.showMessageDialog(parent, "Ha ocurrido un error y la calificacion no pudo ser modificada", "Ooops!!!", JOptionPane.ERROR_MESSAGE,
                            new ImageIcon(getClass().getResource("/presentation/view/images/Exclamation.png")));
                }
                if (jComboBoxTipo.getSelectedItem().equals("Otro") && jTextFieldOtro.getText().equals("")) {
                    JOptionPane.showMessageDialog(parent, "Se debe proporcionar un Tipo de Calificación", "Error!!!", JOptionPane.ERROR_MESSAGE);
                }
                break;
        }
        if (observers.size() > 0) {
            notifyObserver();
            remove(observers.get(0));
        }
    }//GEN-LAST:event_jButtonSaveActionPerformed

    private void jTextFieldOtroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldOtroActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextFieldOtroActionPerformed

    private void jComboBoxTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxTipoActionPerformed
        // TODO add your handling code here:
        if (jComboBoxTipo.getSelectedItem().toString().equals("Otro")) {
            jTextFieldOtro.setEnabled(true);
            jTextFieldOtro.setVisible(true);
        } else {
            jTextFieldOtro.setEnabled(false);
            jTextFieldOtro.setVisible(false);
        }
    }//GEN-LAST:event_jComboBoxTipoActionPerformed

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        parent.dispose();
    }//GEN-LAST:event_jButtonCancelActionPerformed

    private void jSpinnerGradeValueStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSpinnerGradeValueStateChanged
        Double value = new Double((Double) jSpinnerGradeValue.getValue());
        Double perc = new Double(((Double) jSpinnerPonderation.getValue()) / 100);
        Double total = new Double(value * perc);
        jLabelTotalValue.setText(total.toString());
    }//GEN-LAST:event_jSpinnerGradeValueStateChanged

    private void jSpinnerPonderationStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSpinnerPonderationStateChanged
        Double value = new Double((Double) jSpinnerGradeValue.getValue());
        Double perc = new Double(((Double) jSpinnerPonderation.getValue()) / 100);
        Double total = new Double(value * perc);
        jLabelTotalValue.setText(total.toString());
    }//GEN-LAST:event_jSpinnerPonderationStateChanged

    private void jComboBoxSubjectsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxSubjectsActionPerformed
        jSpinnerPonderation.setModel(new javax.swing.SpinnerNumberModel(0.0, 0.0, calculateMaxPercentage(0), 1.0));
    }//GEN-LAST:event_jComboBoxSubjectsActionPerformed

    private void fillComboBoxSubjects() {
        String user = new ControlPanelMyAccount().findByIp().getUsername();
        List<SubjectVO> subjects = new ControlPanelNotes().getSubjectsByUser(user);
        DefaultComboBoxModel comboModel = new DefaultComboBoxModel();
        //comboModel.addElement("Seleccione una materia");
        for (SubjectVO subject : subjects) {
            comboModel.addElement(subject);
        }

        jComboBoxSubjects.setModel(comboModel);
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JComboBox jComboBoxSubjects;
    private javax.swing.JComboBox jComboBoxTipo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabelTotalValue;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSpinner jSpinnerGradeValue;
    private javax.swing.JSpinner jSpinnerPonderation;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextFieldOtro;
    // End of variables declaration//GEN-END:variables

    @Override
    public void attach(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void notifyObserver() {
        for (Observer observer : observers) {
            observer.update();
        }
    }

    @Override
    public void remove(Observer observer) {
        observers.remove(observer);
    }

    private void fillfields() {
        jSpinnerGradeValue.setValue(gradeToUpdate.getValue());
        jSpinnerPonderation.setValue(gradeToUpdate.getPercentage()*100);
        jLabelTotalValue.setText(new Double(gradeToUpdate.getTotal()).toString());
        String type = gradeToUpdate.getType();
        if (!type.equals("Taller") && !type.equals("Laboratorio") && !type.equals("Parcial")
                && !type.equals("Quiz") && !type.equals("Trabajo") && !type.equals("Proyecto")) {
            jComboBoxTipo.setSelectedItem("Otro");
            jTextFieldOtro.setText(type);
        } else {
            jComboBoxTipo.setSelectedItem(type);
        }

    }
}
